package utils

import (
	"bufio"
	"fmt"
	process2 "github.com/ntt360/pmon2/app/svc/process"
	"io"
	"os"
	"path"
	"runtime"
	"strconv"
	"strings"
)

type Intable interface {
	~int | ~int64 | ~int8 | ~int16 | ~int32 | ~uint | ~uint64 | ~uint8 | ~uint16 | ~uint32
}

// GetRootDir 获取项目的绝对路径
func GetRootDir() string {
	ex, _ := os.Executable()
	tmp := strings.ToLower(ex)
	if strings.Contains(tmp, "/tmp/go") {
		_, filename, _, ok := runtime.Caller(0)
		if !ok {
			panic("项目根目录未取得")
		}
		return path.Join(filename, "../..") + string(os.PathSeparator)
	} else {
		return ex[:strings.LastIndex(ex, string(os.PathSeparator))]
	}

}
func GetPm2Conf() string {
	return path.Join(GetRootDir(), "conf/pmon2conf.yml")
}
func GetConf() string {
	return path.Join(GetRootDir(), "conf/config.yml")
}
func Atoi[T Intable](a string) T {
	i, _ := strconv.Atoi(a)
	return T(i)
}
func getSysProcessName(pid int) string {
	procStatus := fmt.Sprintf("/proc/%d/status", pid)
	f, err := os.Open(procStatus)
	if err != nil {
		return ""
	}
	defer f.Close()
	reader := bufio.NewReader(f)
	for {
		line, _, err := reader.ReadLine()
		if err == io.EOF {
			break
		}
		lineStr := string(line)
		if strings.Contains(lineStr, "Name:") || strings.Contains(lineStr, "name:") {
			lineStr = strings.ReplaceAll(lineStr, "Name:", "")
			lineStr = strings.ReplaceAll(lineStr, "name:", "")
			lineStr = strings.TrimSpace(lineStr)
			return lineStr
		}
	}
	return ""
}
func IsRunning(pid int, procName string) bool {
	isRunning := process2.IsRunning(pid)
	if !isRunning {
		return isRunning
	}
	return getSysProcessName(pid) == procName
}
